package FTP;



import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;
import java.io.*;
import staticClasses.URL;

import org.apache.commons.net.ftp.*;

// Kontaktar ftp servern och loggar.
public class FtpClient {

	private String server = "projecthorizon.serveftp.com";
	private int port = 21;
	private String stdFolder = URL.getStdUrl();
	private String serverPath = "";
	private String tempFileName;
	private String username = "admin";
	private String password = "123456";

	public FTPClient client;

	public FtpClient() {

		client = new FTPClient();

		try {
			client.connect(server, port);
			client.login(username, password);

			client.setKeepAlive(true);

		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	// Download the file on the given path to your stdFolder
	public void downloadFile(String path) {
		try {
			/*// Checks all the files in the current directory. The loop is used
			// to
			// find the name of the file and set the outputstream to the same
			// filename.
			for (FTPFile f : client.listFiles()) {
				if (path.endsWith(f.getName())) {
					tempFileName = f.getName();
					break;
				}
				if (path.contains(f.getName())) {
					
					
					client.changeWorkingDirectory(f.getName());
					downloadFile(path);
				}
			}*/
			
			int i = 0;
			int n = 0;
			
			while(i < path.length())
			{
				if (path.charAt(i) == '/'){
					n = i;
				}
				i++;
			}
			
			
			String fileName = path.substring(n+1, path.length());
			

			OutputStream os = new FileOutputStream(getStdFolder()
					+ fileName);
			client.retrieveFile(path, os);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	// Used to get the standard folder
	public String getStdFolder() {
		String strline = "";
		try {
			FileInputStream fstream = new FileInputStream(stdFolder);
			DataInputStream in = new DataInputStream(fstream);

			strline = in.readLine();
			in.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (strline == "") {
			return "You must select a standard folder.";
		} else {
			return strline + "/";
		}
	}

	public String identifyGroupPath(String group) {
		return serverPath + group;
	}
	
	public void disconnect(){
		try {
			client.disconnect();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
